﻿using System;
using System.Data;
using System.Configuration;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;

namespace TA.Turbo.Controls
{
	/// <summary>
	/// Base class for all includes from files in the application directory.
	/// </summary>
	public abstract class BaseFileInclude : BaseInclude
	{
		#region PUBLIC
		#region INIT
		/// <summary>
		/// Ctor.
		/// </summary>
		public BaseFileInclude()
		{
			//
			// TODO: Add constructor logic here
			//
		}
		#endregion
		#region PROPS
		/// <summary>
		/// Gets the contents of the file.
		/// </summary>
		public override string Content
		{
			get
			{
				if (_content == null)
				{
					string path = HttpContext.Current.Server.MapPath(Src);
					if (HttpContext.Current.IsDebuggingEnabled)
					{
						return File.ReadAllText(path);
					}
					else
					{
						DateTime lastWrite = File.GetLastWriteTime(path);

						if (!CachedFileContents.ContainsKey(path) || CachedFileContents[path].LastWriteTime < lastWrite)
							CachedFileContents[path] = new CachedFileContent(lastWrite, File.ReadAllText(path));

						_content = CachedFileContents[path].Content;
					}
				}   
				return _content;
			}
		}
		/// <summary>
		/// Gets the full path of the file, be it a resource or a file.
		/// </summary>
		public override string FileName
		{
			get
			{
				return Src;
			}
		}
		/// <summary>
		/// Gets or sets the virtual path of the file to be included.
		/// </summary>
		[UrlProperty]
		public virtual string Src
		{
			get;
			set;
		}
		#endregion
		#region METHODS
		#endregion
		#endregion
		#region INTERNAL
		#region CONST/STATIC
		const string CachedFileContentsKey = "TA.Turbo.BaseFileInclude.CachedFileContents";
		static Dictionary<string, CachedFileContent> CachedFileContents
		{
			get
			{
				if (HttpContext.Current.Cache[CachedFileContentsKey] == null)
					HttpContext.Current.Cache[CachedFileContentsKey] = new Dictionary<string, CachedFileContent>();
				return (Dictionary<string, CachedFileContent>)HttpContext.Current.Cache[CachedFileContentsKey];
			}
		}
		#endregion
		#region VARS
		string _content;
		#endregion
		#region METHODS
		#endregion
		#endregion

		class CachedFileContent
		{
			public CachedFileContent(DateTime lastWriteTime, string content)
			{
				LastWriteTime = lastWriteTime;
				Content = content;
			}
			public DateTime LastWriteTime;
			public string Content;
		}
	}
}